
import random
from selenium import webdriver
from Lib import _chrome
from time import sleep


def check_again(url, ip_uncheck):
    i = 0
    ip_work = []
    while i < len(ip_uncheck):  # 遍历
        # ip = random.choice(ip_uncheck)
        ip = ip_uncheck[i]
        _chrome.chromeOptions.add_argument("--proxy-server=http://" + ip)  # 设置chrome使用代理ip
        print(ip)
        #for index in range(len(urls)):
            #url = urls[index]
        # 一定要注意，=两边不能有空格，不能是这样--proxy-server = http://202.20.16.82:10152
        driver = webdriver.Chrome(chrome_options=_chrome.chromeOptions)
        driver.set_page_load_timeout(30)  # 设置访问最大延时
        driver.set_script_timeout(30)  # 这两种设置都进行才有效
        try:
            driver.get(url)
            # 随机延时0~20分钟时间
            # sleeptime=round(random.uniform(0,1200),1)
            # sleeptime=1
            # sleep(sleeptime)
            i += 1
            ip_work.append(ip)  # 若代理ip可用则加进用ip中
            print("浏览了" + str(i) + "遍："+url)
            driver.quit()
        except Exception as e:
            driver.close()
            print(str(e))
            print("useless")
    print("--THE IP HAVE BEEN WASHED--")
    return ip_work


def proxy_visit(urls, ip_uncheck):
    for index in range(len(ip_uncheck)):
        ip_uncheck2 = []
        ip = ip_uncheck[index]
        ip_uncheck2.append(ip)
        ip_work = check_again(urls[0], ip_uncheck2)
        i = 0
        while i < len(ip_work):
            a = ip_work[i]
            _chrome.chromeOptions.add_argument("--proxy-server=http://" + a)
            i += 1
            for index2 in range(len(urls)):
                url = urls[index2]
                # 注意：--proxy-server参数的等号=前后不能有空格符号！！！！
                driver = webdriver.Chrome(chrome_options=_chrome.chromeOptions)
                driver.set_page_load_timeout(30)
                driver.set_script_timeout(30)  # 这两种设置都进行才有效
                try:
                    driver.get(url)
                    # 时间间隔在0~10s之内随机访问
                    sleeptime = round(random.uniform(0, 10), 1)
                    sleep(sleeptime)
                    print("浏览了" + str(i) + "遍，时间间隔(秒)==" + str(sleeptime) + ",===========目标网站:" + url)
                    driver.quit()
                except Exception as e:
                    driver.close()
                    print(str(e))
                    print("visit except-----------------")
